package com.firewolf.hibernate.relationship.many_many_both2;

import java.util.HashSet;
import java.util.Set;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class MainDriver {

	private SessionFactory factory;

	private Session session;

	private Transaction transaction;
	
	@Test
	public void saveCustomer(){
		openSession();
		Role r = new Role();
		r.setName("role1");
		
		RoleResource rr = new RoleResource();
		rr.setOther(34);
		RoleResource rr2 = new RoleResource();
		rr2.setOther(35);
		
		Set<RoleResource> rrs = new HashSet<>();
		rrs.add(rr);
		rrs.add(rr2);
		
		r.setRoleResources(rrs);
		session.save(r);
		
		
		closeSession();
	}
	
	private void openSession() {
		session = factory.openSession();
		transaction = session.beginTransaction();
	}
	
	private void closeSession() {
		transaction.commit();
		session.close();
	}

	@Before
	public void init() {
		Configuration cfg = new Configuration().configure("many2many_both2.xml");

		ServiceRegistry registry = new ServiceRegistryBuilder().applySettings(cfg.getProperties())
				.buildServiceRegistry();
		factory = cfg.buildSessionFactory(registry);
	}

	@After
	public void destory() {
		factory.close();
	}
}
